﻿using System;
using Contrib.AppFabric.Models;
using Orchard.Data;
using Orchard.ContentManagement.Handlers;
using Orchard.Environment.Configuration;

namespace Contrib.AppFabric.Handlers {
    public class AppFabricSettingsPartHandler : ContentHandler {
        private readonly ShellSettings _shellSettings;

        public AppFabricSettingsPartHandler(
            IRepository<AppFabricSettingsPartRecord> repository,
            ShellSettings shellSettings) {
            _shellSettings = shellSettings;
            Filters.Add(new ActivatingFilter<AppFabricSettingsPart>("Site"));
            Filters.Add(StorageFilter.For(repository));

            // initializing default cache settings values
            OnInitializing<AppFabricSettingsPart>((context, part) => {
                if (string.IsNullOrWhiteSpace(part.CacheName)) {
                    if (_shellSettings.Name.Equals("default", StringComparison.OrdinalIgnoreCase))
                        part.CacheName = _shellSettings.Name.ToLowerInvariant();

                    part.CacheName = _shellSettings.Name;
                }

                part.SecondsToWaitInRetryCircle = 300;
                part.MaxiumumNumberOfErrorsUntilRetryCircle = 3;
            });

            OnPublishing<AppFabricSettingsPart>((context, part) =>
                                                    {
                                                        if (part.CacheName.Equals("default", StringComparison.OrdinalIgnoreCase))
                                                            part.CacheName = part.CacheName.ToLowerInvariant();
                                                    });
        }
    }
}